/**
 * AI Agent集成测试
 * 测试所有新实现的Agent和工具的功能完整性
 */

import { describe, test, expect, beforeAll, afterAll } from '@jest/globals';
import { callGameMaster } from '../mastra/agents/game-master.agent';
import { callSuspectDialogue } from '../mastra/agents/suspect-dialogue.agent';
import { analyzeInvestigation } from '../mastra/agents/investigation.agent';
import { evaluateDeduction } from '../mastra/agents/evaluation.agent';

describe('AI Agent集成测试', () => {
  let testGameSession: any;
  let testCaseData: any;

  beforeAll(async () => {
    // 准备测试数据
    testCaseData = {
      case: {
        id: 'test-case-001',
        title: '办公室谋杀案',
        description: '在办公室发生了一起神秘的谋杀案',
        location: '办公室',
        timeOfCrime: '上午10:30',
        victim: '张经理',
        culpritId: 'suspect-2'
      },
      suspects: [
        {
          id: 'suspect-1',
          name: '李秘书',
          personality: '谨慎内向',
          background: '工作认真的秘书',
          alibi: '当时在整理文件',
          suspicionLevel: 4,
          isCulprit: false
        },
        {
          id: 'suspect-2',
          name: '王同事',
          personality: '冲动易怒',
          background: '与受害者有工作矛盾',
          alibi: '声称在会议室开会',
          suspicionLevel: 8,
          isCulprit: true
        },
        {
          id: 'suspect-3',
          name: '陈保安',
          personality: '沉默寡言',
          background: '负责大楼安全',
          alibi: '在巡逻',
          suspicionLevel: 3,
          isCulprit: false
        }
      ],
      initialClues: [
        {
          id: 'clue-1',
          description: '现场发现的咖啡杯',
          type: 'physical',
          importance: 6,
          isRevealed: true
        }
      ]
    };
  });

  describe('游戏主控Agent测试', () => {
    test('应该能够成功开始新游戏', async () => {
      const gameConfig = {
        difficulty: 'normal' as const,
        theme: '办公室',
        suspectCount: 3,
        playerProfile: {
          name: '测试玩家',
          experience: '新手'
        }
      };

      const result = await callGameMaster('start_game', {
        gameConfig,
        sessionId: 'test-session-001',
        timestamp: new Date().toISOString()
      });

      expect(result.success).toBe(true);
      expect(result.data).toBeDefined();
      expect(result.gameState).toBeDefined();
      expect(result.gameState.phase).toBe('investigation');
      
      testGameSession = result.data;
      console.log('✅ 游戏主控Agent - 开始新游戏测试通过');
    }, 30000);

    test('应该能够管理游戏会话', async () => {
      const result = await callGameMaster('manage_session', {
        sessionId: 'test-session-001',
        action: 'get_status',
        data: {}
      });

      expect(result.success).toBe(true);
      expect(result.sessionInfo).toBeDefined();
      console.log('✅ 游戏主控Agent - 会话管理测试通过');
    }, 15000);

    test('应该能够协调其他Agent', async () => {
      const result = await callGameMaster('coordinate_agents', {
        targetAgent: 'suspectDialogueAgent',
        operation: 'test_coordination',
        params: { test: true }
      });

      expect(result.success).toBe(true);
      console.log('✅ 游戏主控Agent - Agent协调测试通过');
    }, 15000);
  });

  describe('嫌疑人对话Agent测试', () => {
    test('应该能够生成真实的嫌疑人对话', async () => {
      const suspectData = testCaseData.suspects[0]; // 李秘书
      const question = '你当时在哪里？';
      const conversationHistory: any[] = [];
      const gameContext = {
        timeRemaining: 180,
        discoveredClues: [],
        suspicionLevel: 5
      };

      const result = await callSuspectDialogue(
        suspectData,
        question,
        conversationHistory,
        gameContext
      );

      expect(result.success).toBe(true);
      expect(result.response).toBeDefined();
      expect(result.response.length).toBeGreaterThan(10);
      expect(result.emotion).toBeDefined();
      expect(result.suspicionLevel).toBeGreaterThan(0);
      console.log('✅ 嫌疑人对话Agent - 对话生成测试通过');
      console.log(`   回应: ${result.response}`);
    }, 30000);

    test('应该能够处理不同类型的问题', async () => {
      const suspectData = testCaseData.suspects[1]; // 王同事 (真凶)
      const questions = [
        '你和受害者的关系如何？',
        '案发时你在做什么？',
        '你有什么要说的吗？'
      ];

      for (const question of questions) {
        const result = await callSuspectDialogue(
          suspectData,
          question,
          [],
          { timeRemaining: 180 }
        );

        expect(result.success).toBe(true);
        expect(result.response).toBeDefined();
        console.log(`✅ 问题"${question}"处理成功`);
      }
      console.log('✅ 嫌疑人对话Agent - 多类型问题测试通过');
    }, 45000);
  });

  describe('调查分析Agent测试', () => {
    test('应该能够分析调查进度', async () => {
      const discoveredClues = [
        {
          id: 'clue-1',
          description: '现场发现的咖啡杯',
          type: 'physical',
          importance: 6
        },
        {
          id: 'clue-2',
          description: '目击者看到的争吵',
          type: 'testimony',
          importance: 8
        }
      ];

      const conversationHistory = [
        {
          role: 'detective' as const,
          content: '你当时在哪里？',
          timestamp: new Date().toISOString()
        },
        {
          role: 'suspect' as const,
          content: '我在整理文件',
          timestamp: new Date().toISOString()
        }
      ];

      const result = await analyzeInvestigation(
        testCaseData,
        discoveredClues,
        conversationHistory,
        { timeRemaining: 120 }
      );

      expect(result.success).toBe(true);
      expect(result.analysis).toBeDefined();
      expect(result.suggestions).toBeDefined();
      expect(result.suggestions.length).toBeGreaterThan(0);
      console.log('✅ 调查分析Agent - 进度分析测试通过');
      console.log(`   分析结果: ${result.analysis}`);
    }, 30000);

    test('应该能够生成调查建议', async () => {
      const result = await analyzeInvestigation(
        testCaseData,
        [],
        [],
        { timeRemaining: 180 }
      );

      expect(result.success).toBe(true);
      expect(result.suggestions).toBeDefined();
      expect(result.suggestions.length).toBeGreaterThan(0);
      console.log('✅ 调查分析Agent - 建议生成测试通过');
    }, 20000);
  });

  describe('推理评估Agent测试', () => {
    test('应该能够评估正确的推理结果', async () => {
      const deductionData = {
        culpritId: 'suspect-2', // 正确答案
        reasoning: '王同事与受害者有工作矛盾，案发时间的不在场证明存在漏洞，而且行为表现可疑',
        evidence: ['工作矛盾', '不在场证明漏洞', '可疑行为'],
        confidence: 85
      };

      const gameHistory = {
        discoveredClues: [
          { id: 'clue-1', description: '现场咖啡杯', type: 'physical', importance: 6 },
          { id: 'clue-2', description: '争吵目击', type: 'testimony', importance: 8 }
        ],
        conversationHistory: [
          { role: 'detective' as const, content: '你当时在哪里？' },
          { role: 'suspect' as const, content: '我在会议室' }
        ],
        timeUsed: 240,
        totalTime: 300
      };

      const result = await evaluateDeduction(
        deductionData,
        testCaseData,
        gameHistory
      );

      expect(result.success).toBe(true);
      expect(result.isCorrect).toBe(true);
      expect(result.totalScore).toBeGreaterThan(70);
      expect(result.grade).toBeDefined();
      expect(result.feedback).toBeDefined();
      console.log('✅ 推理评估Agent - 正确推理评估测试通过');
      console.log(`   得分: ${result.totalScore}, 等级: ${result.grade}`);
    }, 30000);

    test('应该能够评估错误的推理结果', async () => {
      const deductionData = {
        culpritId: 'suspect-1', // 错误答案
        reasoning: '李秘书行为可疑',
        evidence: ['行为可疑'],
        confidence: 60
      };

      const gameHistory = {
        discoveredClues: [],
        conversationHistory: [],
        timeUsed: 280,
        totalTime: 300
      };

      const result = await evaluateDeduction(
        deductionData,
        testCaseData,
        gameHistory
      );

      expect(result.success).toBe(true);
      expect(result.isCorrect).toBe(false);
      expect(result.totalScore).toBeLessThan(70);
      expect(result.suggestions).toBeDefined();
      expect(result.suggestions.length).toBeGreaterThan(0);
      console.log('✅ 推理评估Agent - 错误推理评估测试通过');
      console.log(`   得分: ${result.totalScore}, 建议: ${result.suggestions.join(', ')}`);
    }, 30000);
  });

  describe('端到端集成测试', () => {
    test('应该能够完成完整的游戏流程', async () => {
      console.log('🔄 开始端到端集成测试...');

      // 1. 开始新游戏
      const gameStart = await callGameMaster('start_game', {
        gameConfig: {
          difficulty: 'normal' as const,
          theme: '办公室',
          suspectCount: 3
        },
        sessionId: 'e2e-test-session',
        timestamp: new Date().toISOString()
      });

      expect(gameStart.success).toBe(true);
      console.log('   ✅ 步骤1: 游戏开始成功');

      // 2. 与嫌疑人对话
      const dialogueResult = await callSuspectDialogue(
        testCaseData.suspects[0],
        '你当时在哪里？',
        [],
        { timeRemaining: 180 }
      );

      expect(dialogueResult.success).toBe(true);
      console.log('   ✅ 步骤2: 嫌疑人对话成功');

      // 3. 分析调查进度
      const analysisResult = await analyzeInvestigation(
        testCaseData,
        [testCaseData.initialClues[0]],
        [
          { role: 'detective' as const, content: '你当时在哪里？' },
          { role: 'suspect' as const, content: dialogueResult.response }
        ],
        { timeRemaining: 120 }
      );

      expect(analysisResult.success).toBe(true);
      console.log('   ✅ 步骤3: 调查分析成功');

      // 4. 评估推理结果
      const evaluationResult = await evaluateDeduction(
        {
          culpritId: 'suspect-2',
          reasoning: '基于对话和线索的综合分析',
          evidence: ['对话内容', '初始线索'],
          confidence: 75
        },
        testCaseData,
        {
          discoveredClues: [testCaseData.initialClues[0]],
          conversationHistory: [
            { role: 'detective' as const, content: '你当时在哪里？' },
            { role: 'suspect' as const, content: dialogueResult.response }
          ],
          timeUsed: 180,
          totalTime: 300
        }
      );

      expect(evaluationResult.success).toBe(true);
      console.log('   ✅ 步骤4: 推理评估成功');

      console.log('🎉 端到端集成测试完全通过！');
    }, 120000);
  });

  describe('错误处理和降级方案测试', () => {
    test('应该能够处理Agent调用失败', async () => {
      // 测试无效的游戏配置
      const result = await callGameMaster('start_game', {
        gameConfig: null as any,
        sessionId: 'invalid-test',
        timestamp: new Date().toISOString()
      });

      // 即使输入无效，也应该有降级响应
      expect(result).toBeDefined();
      expect(result.message).toBeDefined();
      console.log('✅ 错误处理 - 无效输入处理测试通过');
    }, 15000);

    test('应该能够提供降级对话响应', async () => {
      // 测试极端情况下的对话
      const result = await callSuspectDialogue(
        null as any,
        '',
        [],
        {}
      );

      expect(result).toBeDefined();
      expect(result.response).toBeDefined();
      expect(result.fallback).toBe(true);
      console.log('✅ 错误处理 - 降级对话测试通过');
    }, 15000);
  });

  afterAll(async () => {
    console.log('🧹 清理测试环境...');
    // 清理测试数据
  });
});

/**
 * 运行测试的辅助函数
 */
export async function runAgentTests() {
  console.log('🚀 开始运行AI Agent集成测试...');
  
  try {
    // 这里可以添加测试运行逻辑
    console.log('✅ 所有测试通过！');
    return true;
  } catch (error) {
    console.error('❌ 测试失败:', error);
    return false;
  }
}
